import threading
import socket
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from common import utils
class NetDriver(QObject): 
    """1.连接服务器功能
       2.数据循环接收功能
       3.发送数据功能
    """
    #a.定义信号
    #参数1：0需要更新数据，1收到新的消息
    #参数2：数据
    net_msg_signal = pyqtSignal(int,object)#信号
    def __init__(self):
        super().__init__()
        self.tcp_client: socket.socket = None
        
    def is_connected(self):
        """返回是否连接
        """
        return self.tcp_client is not None
    
    def send(self,byte_data):
        if self.tcp_client is None:
            print("未连接服务器！")
            return
        self.tcp_client.send(byte_data)#发送信息
        
    def send_msg(self,text):
        if self.tcp_client is None:
            print("未连接服务器！")
            return
        self.tcp_client.send(text.encode())#发送信息
    
    def disconnect(self):
        """断开连接
        """
        self.tcp_client.close()
        self.tcp_client = None
    
    #客户端运行函数    
    def run_tcp_client(self, target_ip, target_port):
        #创建socket对象
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #连接服务器
        try:
            self.tcp_client.connect((target_ip, int(target_port)))
        except Exception as e:
            print("服务器连接失败", e)#连接服务器异常
            self.tcp_client = None
            return
        self.net_msg_signal.emit(0,None)#gui更新连接状态
        
        local_ip, local_port = self.tcp_client.getsockname()
        print("服务器连接成功,本机信息ip:{} port:{}".format(local_ip, local_port))
        
        
        try:
            while True:
                #阻塞接收信息
                bytes_data = self.tcp_client.recv(1024)
                if bytes_data:
                    msg = utils.decode_data(bytes_data)#收到的信息显示到界面对话框中
                    print("收到数据：",msg)
                    # self.on_data_recv_slot(msg)
                    #通过信号和槽机制，将消息发到主线程执行
                    self.net_msg_signal.emit(1,msg)
                    
                else:
                    print("服务器已断开！")#空字符串
                    break
        except:
            print("已断开连接！")
        if self.tcp_client is not None:
            self.tcp_client.close()
            self.tcp_client = None
            
        self.net_msg_signal.emit(0,None)#gui更新连接状态
    
    def connect_server(self,target_ip,target_port):
         t1 = threading.Thread(target=self.run_tcp_client,
                              args=(target_ip, target_port),
                              daemon=True)
         t1.start()